{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Non-linear power flow after LOPF \n",
    "\n",
    "In this example, the dispatch of generators is optimised using the linear OPF, then a non-linear power flow is run on the resulting dispatch.\n",
    "\n",
    "## Data sources\n",
    "\n",
    "**Grid:** based on [SciGRID](http://scigrid.de/) Version 0.2 which is based on [OpenStreetMap](http://www.openstreetmap.org/).\n",
    "\n",
    "Load size and location: based on Landkreise (NUTS 3) GDP and population.\n",
    "\n",
    "Load time series: from ENTSO-E hourly data, scaled up uniformly by factor 1.12 (a simplification of the methodology in Schumacher, Hirth (2015)).\n",
    "\n",
    "Conventional power plant capacities and locations: BNetzA list.\n",
    "\n",
    "Wind and solar capacities and locations: EEG Stammdaten, based on  http://www.energymap.info/download.html, which represents capacities at the end of 2014. Units without PLZ are removed.\n",
    "\n",
    "Wind and solar time series: REatlas, Andresen et al, \"Validation of Danish wind time series from a new global renewable energy atlas for energy system analysis,\" Energy 93 (2015) 1074 - 1088.\n",
    "\n",
    "Where SciGRID nodes have been split into 220kV and 380kV substations, all load and generation is attached to the 220kV substation.\n",
    "\n",
    "## Warnings\n",
    "\n",
    "The data behind the notebook is no longer supported. See https://github.com/PyPSA/pypsa-eur for a newer model that covers the whole of Europe.\n",
    "\n",
    "This dataset is ONLY intended to demonstrate the capabilities of PyPSA and is NOT (yet) accurate enough to be used for research purposes.\n",
    "\n",
    "Known problems include:\n",
    "\n",
    "1. Rough approximations have been made for missing grid data, e.g. 220kV-380kV transformers and connections between close sub-stations missing from OSM.\n",
    "\n",
    "2. There appears to be some unexpected congestion in parts of the network, which may mean for example that the load attachment method (by Voronoi cell overlap with Landkreise) isn't working, particularly in regions with a high density of substations.\n",
    "\n",
    "3. Attaching power plants to the nearest high voltage substation may not reflect reality.\n",
    "\n",
    "4. There is no proper n-1 security in the calculations - this can either be simulated with a blanket e.g. 70% reduction in thermal limits (as done here) or a proper security constrained OPF (see e.g.  <http://www.pypsa.org/examples/scigrid-sclopf.ipynb>).\n",
    "\n",
    "5. The borders and neighbouring countries are not represented.\n",
    "\n",
    "6. Hydroelectric power stations are not modelled accurately.\n",
    "\n",
    "7. The marginal costs are illustrative, not accurate.\n",
    "\n",
    "8. Only the first day of 2011 is in the github dataset, which is not representative. The full year of 2011 can be downloaded at <http://www.pypsa.org/examples/scigrid-with-load-gen-trafos-2011.zip>.\n",
    "\n",
    "9. The ENTSO-E total load for Germany may not be scaled correctly; it is scaled up uniformly by factor 1.12 (a simplification of the methodology in Schumacher, Hirth (2015), which suggests monthly factors).\n",
    "\n",
    "10. Biomass from the EEG Stammdaten are not read in at the moment.\n",
    "\n",
    "11. Power plant start up costs, ramping limits/costs, minimum loading rates are not considered.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import pypsa\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "import cartopy.crs as ccrs\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "network = pypsa.examples.scigrid_de(from_master=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plot the distribution of the load and of generating tech"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "fig,ax = plt.subplots(1,1,subplot_kw={\"projection\":ccrs.EqualEarth()}, figsize=(8,8))\n",
    "\n",
    "load_distribution = (network.loads_t.p_set.loc[network.snapshots[0]]\n",
    "                     .groupby(network.loads.bus).sum())\n",
    "network.plot(bus_sizes=1e-5*load_distribution, ax=ax, title=\"Load distribution\");\n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "network.generators.groupby(\"carrier\")[\"p_nom\"].sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "network.storage_units.groupby(\"carrier\")[\"p_nom\"].sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "techs = [\"Gas\", \"Brown Coal\", \"Hard Coal\", \"Wind Offshore\", \"Wind Onshore\", \"Solar\"]\n",
    "\n",
    "n_graphs = len(techs)\n",
    "n_cols = 3\n",
    "if n_graphs % n_cols == 0:\n",
    "    n_rows = n_graphs // n_cols\n",
    "else:\n",
    "    n_rows = n_graphs // n_cols + 1\n",
    "\n",
    "    \n",
    "fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols, subplot_kw={\"projection\":ccrs.EqualEarth()})\n",
    "size = 6\n",
    "fig.set_size_inches(size*n_cols,size*n_rows)\n",
    "\n",
    "for i,tech in enumerate(techs):\n",
    "    i_row = i // n_cols\n",
    "    i_col = i % n_cols\n",
    "    \n",
    "    ax = axes[i_row,i_col]\n",
    "    gens = network.generators[network.generators.carrier == tech]\n",
    "    gen_distribution = gens.groupby(\"bus\").sum()[\"p_nom\"].reindex(network.buses.index,fill_value=0.)\n",
    "    network.plot(ax=ax,bus_sizes=2e-5*gen_distribution)\n",
    "    ax.set_title(tech)\n",
    "fig.tight_layout()  \n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Run Linear Optimal Power Flow on the first day of 2011.\n",
    "\n",
    "To approximate n-1 security and allow room for reactive power flows, don't allow any line to be loaded above 70% of their thermal rating"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "contingency_factor = 0.7\n",
    "network.lines.s_max_pu = contingency_factor"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are some infeasibilities without small extensions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network.lines.loc[[\"316\",\"527\",\"602\"],\"s_nom\"] = 1715"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We performing a linear OPF for one day, 4 snapshots at a time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "group_size = 4\n",
    "network.storage_units.state_of_charge_initial = 0.\n",
    "\n",
    "for i in range(int(24/group_size)):\n",
    "    #set the initial state of charge based on previous round\n",
    "    if i:\n",
    "        network.storage_units.state_of_charge_initial = (\n",
    "            network.storage_units_t.state_of_charge.loc[network.snapshots[group_size*i-1]])\n",
    "    network.lopf(network.snapshots[group_size*i:group_size*i+group_size], solver_name='cbc', \n",
    "                pyomo=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "p_by_carrier = network.generators_t.p.groupby(network.generators.carrier, axis=1).sum()\n",
    "p_by_carrier.drop((p_by_carrier.max()[p_by_carrier.max() < 1700.]).index,axis=1,inplace=True)\n",
    "p_by_carrier.columns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "colors = {\"Brown Coal\" : \"brown\",\n",
    "          \"Hard Coal\" : \"k\",\n",
    "          \"Nuclear\" : \"r\",\n",
    "          \"Run of River\" : \"green\",\n",
    "          \"Wind Onshore\" : \"blue\",\n",
    "          \"Solar\" : \"yellow\",\n",
    "          \"Wind Offshore\" : \"cyan\",\n",
    "          \"Waste\" : \"orange\",\n",
    "          \"Gas\" : \"orange\"}\n",
    "#reorder\n",
    "cols = [\"Nuclear\",\"Run of River\",\"Brown Coal\",\"Hard Coal\",\"Gas\",\"Wind Offshore\",\"Wind Onshore\",\"Solar\"]\n",
    "p_by_carrier = p_by_carrier[cols]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "c = [colors[col] for col in p_by_carrier.columns]\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(12, 6))\n",
    "(p_by_carrier/1e3).plot(kind=\"area\", ax=ax, linewidth=4, color=c, alpha=.7)\n",
    "ax.legend(ncol=4,loc=\"upper left\")\n",
    "ax.set_ylabel(\"GW\")\n",
    "ax.set_xlabel(\"\")\n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize = (12,6))\n",
    "\n",
    "p_storage = network.storage_units_t.p.sum(axis=1)\n",
    "state_of_charge = network.storage_units_t.state_of_charge.sum(axis=1)\n",
    "p_storage.plot(label=\"Pumped hydro dispatch\",ax=ax,linewidth=3)\n",
    "state_of_charge.plot(label=\"State of charge\",ax=ax,linewidth=3)\n",
    "\n",
    "ax.legend()\n",
    "ax.grid()\n",
    "ax.set_ylabel(\"MWh\")\n",
    "ax.set_xlabel(\"\")\n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "now = network.snapshots[4]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the linear load flow, there is the following per unit loading:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "loading = network.lines_t.p0.loc[now]/network.lines.s_nom\n",
    "loading.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(subplot_kw={\"projection\":ccrs.EqualEarth()}, figsize=(9,9))\n",
    "network.plot(ax=ax, line_colors=abs(loading), line_cmap=plt.cm.jet, title=\"Line loading\",\n",
    "            bus_sizes=1e-3, bus_alpha=.7)\n",
    "fig.tight_layout();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's have a look at the marginal prices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "network.buses_t.marginal_price.loc[now].describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(subplot_kw={\"projection\":ccrs.PlateCarree()}, figsize=(8,8))\n",
    "\n",
    "plt.hexbin(network.buses.x, network.buses.y, \n",
    "           gridsize=20,\n",
    "           C=network.buses_t.marginal_price.loc[now],\n",
    "           cmap=plt.cm.jet, \n",
    "           zorder=3)\n",
    "network.plot(ax=ax,\n",
    "             line_widths=pd.Series(0.5, network.lines.index), \n",
    "             bus_sizes=0)\n",
    "\n",
    "cb = plt.colorbar(location='bottom')\n",
    "cb.set_label('Locational Marginal Price (EUR/MWh)') \n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Curtailment variable\n",
    "\n",
    "By considering how much power is available and how much is generated, you can see what share is curtailed: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "carrier = \"Wind Onshore\"\n",
    "\n",
    "capacity = network.generators.groupby(\"carrier\").sum().at[carrier,\"p_nom\"]\n",
    "p_available = network.generators_t.p_max_pu.multiply(network.generators[\"p_nom\"])\n",
    "p_available_by_carrier = p_available.groupby(network.generators.carrier, axis=1).sum()\n",
    "p_curtailed_by_carrier = p_available_by_carrier - p_by_carrier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p_df = pd.DataFrame({carrier + \" available\" : p_available_by_carrier[carrier],\n",
    "                     carrier + \" dispatched\" : p_by_carrier[carrier],\n",
    "                     carrier + \" curtailed\" : p_curtailed_by_carrier[carrier]})\n",
    "\n",
    "p_df[carrier + \" capacity\"] = capacity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "p_df[\"Wind Onshore curtailed\"][p_df[\"Wind Onshore curtailed\"] < 0.] = 0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "fig,ax = plt.subplots(figsize=(10,4))\n",
    "p_df[[carrier + \" dispatched\",carrier + \" curtailed\"]].plot(kind=\"area\",ax=ax,linewidth=3)\n",
    "p_df[[carrier + \" available\",carrier + \" capacity\"]].plot(ax=ax,linewidth=3)\n",
    "\n",
    "ax.set_xlabel(\"\")\n",
    "ax.set_ylabel(\"Power [MW]\")\n",
    "ax.set_ylim([0,40000])\n",
    "ax.legend()\n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Non-Linear Power Flow\n",
    "\n",
    "Now perform a full Newton-Raphson power flow on the first hour. For the PF, set the P to the optimised P."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "network.generators_t.p_set = network.generators_t.p\n",
    "network.storage_units_t.p_set = network.storage_units_t.p"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Set all buses to PV, since we don't know what Q set points are"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "network.generators.control = \"PV\"\n",
    "\n",
    "#Need some PQ buses so that Jacobian doesn't break\n",
    "f = network.generators[network.generators.bus == \"492\"]\n",
    "network.generators.loc[f.index,\"control\"] = \"PQ\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, perform the non-linear PF."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "info = network.pf();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Any failed to converge?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(~info.converged).any().any()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the non-linear load flow, there is the following per unit loading of the full thermal rating."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "(network.lines_t.p0.loc[now]/network.lines.s_nom).describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's inspect the voltage angle differences across the lines have (in degrees)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "df = network.lines.copy()\n",
    "\n",
    "for b in [\"bus0\",\"bus1\"]:\n",
    "    df = pd.merge(df,network.buses_t.v_ang.loc[[now]].T,how=\"left\",\n",
    "         left_on=b,right_index=True)\n",
    "\n",
    "s = df[str(now)+\"_x\"]- df[str(now)+\"_y\"]\n",
    "\n",
    "(s*180/np.pi).describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plot the reactive power"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "fig,ax = plt.subplots(subplot_kw={\"projection\":ccrs.EqualEarth()}, figsize=(9,9))\n",
    "\n",
    "q = network.buses_t.q.loc[now]\n",
    "bus_colors = pd.Series(\"r\",network.buses.index)\n",
    "bus_colors[q< 0.] = \"b\"\n",
    "\n",
    "network.plot(bus_sizes=1e-4*abs(q),ax=ax,bus_colors=bus_colors,\n",
    "             title=\"Reactive power feed-in (red=+ve, blue=-ve)\");"
   ]
  }
 ],
 "metadata": {
  "@webio": {
   "lastCommId": null,
   "lastKernelId": null
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
